import startCurdConfig from "./startCurdConfig";
import startBaseCrud from "@/mixins/startBaseCrud";

/**
 * 创建动态crud mixins
 * @param option
 * @returns mixin
 */
export function createDynamicMixin(option = {}) {
    return {
        mixins: [startBaseCrud.createMixin(option)],
        computed: {
            pageOption() {
                return option;
            },
        },
        data() {
            this.initCrudOptionConfig();
            return {}
        },
        methods: {
            initCrudOptionConfig() {
                let apiPath = option.apiPath || option.name
                let apiObj = startCurdConfig.getApi(`../api/${apiPath + (option.optionSuffix || 'Api')}.js`)
                let apiModel = null;
                apiObj().then(mode => {
                    if (Object.keys(mode).length < 2 && Object.keys(mode)[0] === 'default') {
                        if (mode.default instanceof Function) {
                            mode = mode.default(this);
                        } else {
                            mode = mode.default;
                        }
                    }
                    apiModel = mode
                    let optionPath = option.optionPath || option.name
                    let optionObj = startCurdConfig.getOption(`../option/${optionPath + (option.optionSuffix || 'Option')}.js`)
                    return optionObj()
                }).then(avueOption => {
                    avueOption = avueOption.default(this);
                    this.loadCrudOptionConfig(avueOption, apiModel)
                })
            },
        },
    }
}

/**
 * 创建静态crud mixins
 * @param option
 * @returns  mixin
 */
export function createStaticMixin(option) {

    return {
        mixins: [startBaseCrud.createMixin(option)],
        computed: {
            pageOption() {
                return option;
            },
        },
        data() {
            if (option.option === null) {
                console.warn("option 不能为空")
            }
            if (option.api === null) {
                console.warn("api 不能为空")
            }
            let avueOption = option.option
            if (option.option instanceof Function) {
                avueOption = option.option(this)
            }
            const apiModel = option.api;
            this.$nextTick(() => this.loadCrudOptionConfig(avueOption, apiModel))
            return {}
        },
    }
}

const startCrud = {}
startCrud.createDynamicMixin = createDynamicMixin;
startCrud.createStaticMixin = createStaticMixin;
export default startCrud
